var util = {};

util.api = function (action, querystring) {
    var app = getApp();
    var url = app.siteroot;
    if (action) url += action;

    if (querystring && typeof querystring === 'object') {
        for (let param in querystring) {
            if (param && querystring.hasOwnProperty(param) && querystring[param]) {
                url += '&' + param + '=' + querystring[param];
            }
        }
    }
    return url;
}
util.request = function (option) {
    var app = getApp();
    var option = option ? option : {};
    option.cachetime = option.cachetime ? option.cachetime : 0;
    option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : false;
    option.mask = typeof option.mask != 'undefined' ? option.mask : false;

    var token = app.token;
    var url = option.url;
    if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
        url = util.api(url);
    }
    let header = option.header ? option.header : {};
    header['content-type'] = 'application/x-www-form-urlencoded';
    if (header && token) {
        header['Cookie'] = "JSESSIONID=" + token
    } else {
        util.login(function () {
            console.log("登录失败", option)
            util.request(option)
        })
        return;
    }

    if (!url) {
        return false;
    }

    if (option.showLoading) {
        util.showLoading(option.mask);
        wx.showNavigationBarLoading();
    }
    if (option.cachetime) {
        var cachekey = md5(url);
        var cachedata = wx.getStorageSync(cachekey);
        var timestamp = Date.parse(new Date());

        if (cachedata && cachedata.data) {
            if (cachedata.expire > timestamp) {
                if (option.success && typeof option.success == 'function') {
                    option.success(cachedata);
                }
                if (option.complete && typeof option.complete == 'function') {
                    option.complete(cachedata);
                }
                console.log('命中缓存:' + url);
                wx.hideLoading();
                wx.hideNavigationBarLoading();
                return true;
            } else {
                wx.removeStorageSync(cachekey)
            }
        }
    }
    wx.request({
        url: url,
        data: option.data ? option.data : {},
        header: header,
        method: option.method ? option.method : 'POST',
        success: function (response) {
            wx.hideNavigationBarLoading();
            wx.hideLoading();
            if (typeof (response.header.token) != 'undefined') {
                app.token = response.header.token;
            }
            if (response.data.code == 0 || response.data.code == 203 || response.data.code == 500) {
                if (response.data.code == 203) {
                    wx.reLaunch({
                      url: '/pages/login/login',
                    })
                    return
                    util.request(option)
                }
                if (option.success && typeof option.success == 'function') {
                    option.success(response);
                }
            } else {
                if (option.success && typeof option.success == 'function') {
                    option.success(response);
                }
                if (option.cachetime) {
                    var cachedata = {
                        'data': response.data,
                        'expire': timestamp + option.cachetime * 1000
                    };
                    wx.setStorageSync(cachekey, cachedata);
                }
            }
        },
        fail: function (response) {
            wx.hideNavigationBarLoading();
            wx.hideLoading();
            var md5 = require('md5.js');
            var cachekey = md5(url);
            var cachedata = wx.getStorageSync(cachekey);
            if (cachedata && cachedata.data) {
                if (option.success && typeof option.success == 'function') {
                    option.success(cachedata);
                }
                console.log('请求失败读取缓存:' + url);
                return true;
            } else {
                if (option.fail && typeof option.fail == 'function') {
                    option.fail(response);
                }
            }
        },
        complete: function (response) {
            if (option.complete && typeof option.complete == 'function') {
                option.complete(response);
            }
        }
    });
}
util.login = function (callback = function () { }) {
    let app = getApp();
    let header = {};
    if (app.is_loging) {
        let detect_login_complete = setInterval(function () {
            console.info('检测login中')
            if (!app.is_loging) {
                console.info('请求login完成')
                callback();
                clearInterval(detect_login_complete);
            }
        }, 200);
    }
    app.is_loging = true;
    wx.login({
        success(res) {
            wx.request({
                url: util.api("app/login"),
                header: header,
                method: "POST",
                data: {
                    code: res.code
                },
                success(response) {
                    if (response.statusCode == 200 && response.data.code == 200) {
                        app.token = response.data.data;
                        callback();
                    }
                },
                complete() {
                    app.is_loging = false;
                }
            })
        }
    })
}
util.navigateBack = function (obj) {
    let delta = obj.delta ? obj.delta : 1;
    if (obj.data) {
        let pages = getCurrentPages()
        let curPage = pages[pages.length - (delta + 1)];
        if (curPage.pageForResult) {
            curPage.pageForResult(obj.data);
        } else {
            curPage.setData(obj.data);
        }
    }
    wx.navigateBack({
        delta: delta,
        success: function (res) {
            typeof obj.success == "function" && obj.success(res);
        },
        fail: function (err) {
            typeof obj.fail == "function" && obj.fail(err);
        },
        complete: function () {
            typeof obj.complete == "function" && obj.complete();
        }
    })
};
util.message = function (title, redirect, type) {
    if (!title) {
        return true;
    }
    if (typeof title == 'object') {
        redirect = title.redirect;
        type = title.type;
        title = title.title;
    }
    if (redirect) {
        var redirectType = redirect.substring(0, 9),
            url = '',
            redirectFunction = '';
        if (redirectType == 'navigate:') {
            redirectFunction = 'navigateTo';
            url = redirect.substring(9);
        } else if (redirectType == 'redirect:') {
            redirectFunction = 'redirectTo';
            url = redirect.substring(9);
        } else {
            url = redirect;
            redirectFunction = 'redirectTo';
        }
    }
    console.log(url)
    if (!type) {
        type = 'success';
    }

    if (type == 'success') {
        wx.showToast({
            title: title,
            icon: 'success',
            duration: 2000,
            mask: url ? true : false,
            complete: function () {
                if (url) {
                    setTimeout(function () {
                        wx[redirectFunction]({
                            url: url,
                        });
                    }, 1800);
                }

            }
        });
    } else if (type == 'error') {
        wx.showModal({
            title: '系统信息',
            content: title,
            showCancel: false,
            complete: function () {
                if (url) {
                    wx[redirectFunction]({
                        url: url,
                    });
                }
            }
        });
    }
}
util.showLoading = function (mask = false) {
    var isShowLoading = wx.getStorageSync('isShowLoading');
    if (isShowLoading) {
        wx.hideLoading();
        wx.setStorageSync('isShowLoading', false);
    }

    wx.showLoading({
        title: '加载中',
        mask: mask,
        complete: function () {
            wx.setStorageSync('isShowLoading', true);
        },
        fail: function () {
            wx.setStorageSync('isShowLoading', false);
        }
    });
}

util.showImage = function (event) {
    var url = event ? event.currentTarget.dataset.preview : '';
    if (!url) {
        return false;
    }
    wx.previewImage({
        urls: [url]
    });
}
util.parseContent = function (string) {
    if (!string) {
        return string;
    }

    var ranges = [
        '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
        '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
        '\ud83d[\ude80-\udeff]' // U+1F680 to U+1F6FF
    ];
    var emoji = string.match(
        new RegExp(ranges.join('|'), 'g'));

    if (emoji) {
        for (var i in emoji) {
            string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
        }
    }
    return string;
}


module.exports = util;
